// 小兵类
class Minion {
    constructor(x, y) {
        const base = BALANCE_CONFIG.MINIONS.base;
        this.x = x;
        this.y = y;
        this.size = base.size;
        this.speed = base.speed;
        this.health = base.health;
        this.maxHealth = base.health;
        this.isDead = false;
        this.color = '#32CD32';

        // 小兵成长系统
        this.level = 1;
        this.killCount = 0;
        this.experience = 0;
        this.experienceToNextLevel = 50; // 可后续用balanceConfig配置
        this.survivalTime = 0;

        // AI相关
        this.target = null;
        this.searchRadius = base.attackRange * 1.5; // 搜索半径=攻击范围*1.5
        this.wanderRadius = 100;
        this.wanderCenter = { x: this.x, y: this.y };
        this.wanderAngle = Math.random() * Math.PI * 2;
        this.wanderSpeed = 0.02;
        this.avoidanceRange = base.avoidanceRadius;

        // 攻击相关
        this.attackCooldown = base.attackCooldown;
        this.lastAttackTime = 0;
        this.attackRange = base.attackRange;
        this.damage = base.damage;
        this.projectileSpeed = base.projectileSpeed;

        // 跟随玩家相关
        this.followPlayer = true;
        this.followDistance = 150;
        this.followSpeed = 0.8;
    }

    update(deltaTime, enemies) {
        if (this.isDead) return;
        this.survivalTime += deltaTime;
        this.updateGrowth(deltaTime);
        this.updateAI(deltaTime, enemies);
        this.updateAttack(deltaTime, enemies);
        this.updateProjectiles(deltaTime, enemies);
        this.updateFollowPlayer(deltaTime);
    }

    updateGrowth(deltaTime) {
        if (this.survivalTime >= 15000) {
            this.gainExperience(20);
            this.survivalTime = 0;
        }
    }

    gainExperience(amount) {
        this.experience += amount;
        if (this.experience >= this.experienceToNextLevel) {
            this.levelUp();
        }
    }

    levelUp() {
        const perLevel = BALANCE_CONFIG.MINIONS.perLevel;
        this.level++;
        this.experience -= this.experienceToNextLevel;
        this.experienceToNextLevel = Math.floor(this.experienceToNextLevel * 1.2);
        // 属性提升
        this.maxHealth += perLevel.health;
        this.health = this.maxHealth;
        this.damage += perLevel.damage;
        this.speed += perLevel.speed;
        this.attackCooldown = Math.max(100, this.attackCooldown + perLevel.attackCooldown); // perLevel.attackCooldown为负数
        this.attackRange += perLevel.attackRange;
        this.projectileSpeed += perLevel.projectileSpeed;
        this.avoidanceRange += perLevel.avoidanceRadius || 0;
        // 显示升级效果
        if (window.uiManager) {
            window.uiManager.showMessage(`小兵升级到 ${this.level} 级！`, 2000);
        }
        console.log(`小兵升级到 ${this.level} 级！伤害: ${this.damage}, 攻击范围: ${this.attackRange}`);
    }

    onKillEnemy() {
        this.killCount++;
        this.gainExperience(30);
    }

    updateFollowPlayer(deltaTime) {
        if (!this.followPlayer || !window.game || !window.game.player) return;
        const player = window.game.player;
        const distanceToPlayer = Utils.distance(this.x, this.y, player.x, player.y);
        if (distanceToPlayer > this.followDistance) {
            const angle = Utils.angle(this.x, this.y, player.x, player.y);
            const moveSpeed = this.speed * this.followSpeed * (deltaTime / 16.67);
            this.x += Math.cos(angle) * moveSpeed;
            this.y += Math.sin(angle) * moveSpeed;
            this.x = Utils.clamp(this.x, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
            this.y = Utils.clamp(this.y, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
        }
    }

    updateAI(deltaTime, enemies) {
        const nearestEnemy = this.findNearestEnemy(enemies);
        if (nearestEnemy && this.getDistanceToEnemy(nearestEnemy) <= this.searchRadius) {
            this.target = nearestEnemy;
            this.maintainDistance(deltaTime, nearestEnemy);
        } else {
            this.wander(deltaTime);
        }
    }

    maintainDistance(deltaTime, enemy) {
        const distance = this.getDistanceToEnemy(enemy);
        const idealDistance = this.attackRange * 0.7;
        if (distance < idealDistance) {
            const angle = Utils.angle(enemy.x, enemy.y, this.x, this.y);
            const moveSpeed = this.speed * (deltaTime / 16.67);
            const targetX = this.x + Math.cos(angle) * moveSpeed;
            const targetY = this.y + Math.sin(angle) * moveSpeed;
            this.x = targetX;
            this.y = targetY;
        } else if (distance > this.attackRange) {
            const angle = Utils.angle(this.x, this.y, enemy.x, enemy.y);
            const moveSpeed = this.speed * (deltaTime / 16.67);
            const targetX = this.x + Math.cos(angle) * moveSpeed;
            const targetY = this.y + Math.sin(angle) * moveSpeed;
            this.x = targetX;
            this.y = targetY;
        }
        this.x = Utils.clamp(this.x, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
        this.y = Utils.clamp(this.y, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
        this.wanderCenter.x = this.x;
        this.wanderCenter.y = this.y;
    }

    findNearestEnemy(enemies) {
        let nearestEnemy = null;
        let nearestDistance = Infinity;
        enemies.forEach(enemy => {
            if (!enemy.isDead) {
                const distance = this.getDistanceToEnemy(enemy);
                if (distance < nearestDistance) {
                    nearestDistance = distance;
                    nearestEnemy = enemy;
                }
            }
        });
        return nearestEnemy;
    }

    chaseTarget(deltaTime) {
        if (!this.target) return;
        const angle = Utils.angle(this.x, this.y, this.target.x, this.target.y);
        const targetPos = Utils.getPositionFromAngle(this.x, this.y, angle, this.speed);
        this.x = targetPos.x;
        this.y = targetPos.y;
        this.x = Utils.clamp(this.x, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
        this.y = Utils.clamp(this.y, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
        this.wanderCenter.x = this.x;
        this.wanderCenter.y = this.y;
    }

    wander(deltaTime) {
        this.wanderAngle += this.wanderSpeed * deltaTime;
        const targetX = this.wanderCenter.x + Math.cos(this.wanderAngle) * this.wanderRadius;
        const targetY = this.wanderCenter.y + Math.sin(this.wanderAngle) * this.wanderRadius;
        const moveSpeed = 0.02 * deltaTime / 16.67;
        this.x += (targetX - this.x) * moveSpeed;
        this.y += (targetY - this.y) * moveSpeed;
        this.x = Utils.clamp(this.x, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
        this.y = Utils.clamp(this.y, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
    }

    updateAttack(deltaTime, enemies) {
        this.lastAttackTime += deltaTime;
        if (this.lastAttackTime >= this.attackCooldown) {
            const nearestEnemy = this.findNearestEnemy(enemies);
            if (nearestEnemy && this.getDistanceToEnemy(nearestEnemy) <= this.attackRange) {
                this.fireProjectile(nearestEnemy);
                this.lastAttackTime = 0;
                console.log(`小兵攻击敌人！距离: ${this.getDistanceToEnemy(nearestEnemy)}, 伤害: ${this.damage}`);
            }
        }
    }

    fireProjectile(target) {
        const angle = Utils.angle(this.x, this.y, target.x, target.y);
        const projectile = new MinionProjectile(this.x, this.y, angle, this.damage, this.level, this.projectileSpeed);
        this.projectiles.push(projectile);
        console.log(`小兵发射弹丸！位置: (${this.x}, ${this.y}), 目标: (${target.x}, ${target.y}), 角度: ${angle}`);
    }

    updateProjectiles(deltaTime, enemies) {
        this.projectiles.forEach(projectile => {
            projectile.update(deltaTime);
            enemies.forEach(enemy => {
                if (!enemy.isDead && projectile.collidesWith(enemy)) {
                    enemy.takeDamage(projectile.damage);
                    projectile.die();
                    if (enemy.isDead) {
                        this.onKillEnemy();
                    }
                    if (window.uiManager) {
                        window.uiManager.showDamageNumber(enemy.x, enemy.y - 30, projectile.damage);
                    }
                    console.log(`小兵弹丸击中敌人！伤害: ${projectile.damage}`);
                }
            });
        });
        this.projectiles = this.projectiles.filter(projectile => !projectile.isDead);
    }

    getDistanceToEnemy(enemy) {
        return Utils.distance(this.x, this.y, enemy.x, enemy.y);
    }

    takeDamage(damage) {
        this.health -= damage;
        this.health = Math.max(0, this.health);
        if (this.health <= 0) {
            this.die();
        }
    }

    die() {
        this.isDead = true;
    }

    render(ctx) {
        if (this.isDead) return;
        ctx.save();
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 1;
        ctx.stroke();
        ctx.fillStyle = '#ffffff';
        ctx.font = '8px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('M', this.x, this.y + 2);
        ctx.fillStyle = '#FFD700';
        ctx.font = '6px Arial';
        ctx.fillText(this.level.toString(), this.x, this.y - this.size - 5);
        this.renderHealthBar(ctx);
        if (window.game && window.game.debugMode) {
            ctx.strokeStyle = '#00FF00';
            ctx.lineWidth = 1;
            ctx.globalAlpha = 0.3;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.attackRange, 0, Math.PI * 2);
            ctx.stroke();
            ctx.globalAlpha = 1;
        }
        ctx.restore();
    }

    renderHealthBar(ctx) {
        const barWidth = this.size * 2;
        const barHeight = 3;
        const barX = this.x - barWidth / 2;
        const barY = this.y - this.size - 10;
        ctx.fillStyle = '#333333';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        const healthPercent = this.health / this.maxHealth;
        ctx.fillStyle = healthPercent > 0.5 ? '#00FF00' : healthPercent > 0.25 ? '#FFFF00' : '#FF0000';
        ctx.fillRect(barX, barY, barWidth * healthPercent, barHeight);
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 1;
        ctx.strokeRect(barX, barY, barWidth, barHeight);
    }

    collidesWith(other) {
        return Utils.rectCollision(
            this.x - this.size, this.y - this.size, this.size * 2, this.size * 2,
            other.x - (other.size || 0), other.y - (other.size || 0),
            (other.size || 0) * 2, (other.size || 0) * 2
        );
    }
}

// 小兵弹丸类
class MinionProjectile {
    constructor(x, y, angle, damage, level, speed) {
        this.x = x;
        this.y = y;
        this.angle = angle;
        this.speed = speed || 6;
        this.damage = damage;
        this.level = level;
        this.size = 5; // 尺寸增大
        this.lifetime = 2000;
        this.maxLifetime = 2000;
        this.isDead = false;
        this.color = '#FFD700'; // 金黄色
    }
    update(deltaTime) {
        if (this.isDead) return;
        const moveSpeed = this.speed * (deltaTime / 16.67);
        this.x += Math.cos(this.angle) * moveSpeed;
        this.y += Math.sin(this.angle) * moveSpeed;
        this.lifetime -= deltaTime;
        if (this.lifetime <= 0) {
            this.die();
        }
        if (this.x < 0 || this.x > GAME_CONFIG.WORLD_WIDTH ||
            this.y < 0 || this.y > GAME_CONFIG.WORLD_HEIGHT) {
            this.die();
        }
    }
    render(ctx) {
        if (this.isDead) return;
        ctx.save();
        const alpha = Math.max(0.5, this.lifetime / this.maxLifetime); // 最低透明度0.5
        ctx.globalAlpha = alpha;
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        // 增加白色描边
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 2;
        ctx.stroke();
        ctx.restore();
    }
    die() {
        this.isDead = true;
    }
    collidesWith(other) {
        return Utils.rectCollision(
            this.x - this.size, this.y - this.size, this.size * 2, this.size * 2,
            other.x - (other.size || 0), other.y - (other.size || 0),
            (other.size || 0) * 2, (other.size || 0) * 2
        );
    }
}

// 小兵管理器
class MinionManager {
    constructor() {
        this.minions = [];
    }
    addMinion(x, y) {
        const minion = new Minion(x, y);
        this.minions.push(minion);
        console.log(`添加了小兵在位置 (${x}, ${y})`);
        return minion;
    }
    update(deltaTime, enemies) {
        this.minions.forEach(minion => {
            minion.update(deltaTime, enemies);
        });
        this.cleanupDeadMinions();
    }
    cleanupDeadMinions() {
        this.minions = this.minions.filter(minion => !minion.isDead);
    }
    render(ctx) {
        this.minions.forEach(minion => {
            minion.render(ctx);
        });
    }
    getMinionCount() {
        return this.minions.length;
    }
    getAverageLevel() {
        if (this.minions.length === 0) return 0;
        const totalLevel = this.minions.reduce((sum, minion) => sum + minion.level, 0);
        return Math.round(totalLevel / this.minions.length);
    }
    reset() {
        this.minions = [];
    }
} 